#!/bin/bash
# Tomcat多机部署脚本
# 注：此脚本只用于***开发/测试服务器的Tomcat2部署

# 常量
SERVER_INTRANET_IP="127.0.0.1"
SERVER1_INTRANET_IP="172.17.0.1"
SERVER2_INTRANET_IP="172.18.68.207"

SERVER2_USER="ecs-user"

TOMCAT1_PORT="11003"
TOMCAT1_CATALINA_HOME="/opt/naoyihui_tomcat_user"
TOMCAT1_DEPLOY_DIRECTORY="$TOMCAT1_CATALINA_HOME/webapps/"

TOMCAT2_PORT="11003"
TOMCAT2_CATALINA_HOME="/opt/naoyihui_tomcat_user"
TOMCAT2_DEPLOY_DIRECTORY="$TOMCAT2_CATALINA_HOME/webapps/"

NGINX_CONFIG_DIRECTORY="/opt/nginx"
NGINX_CONFIG_FILE_MEDTION="$NGINX_CONFIG_DIRECTORY/conf/sites-available/dev.medtion.com.conf"
NGINX_CONFIG_FILE_BRAINMED="$NGINX_CONFIG_DIRECTORY/conf/sites-available/dev.brainmed.com.conf"
TAB="    "
NGINX_UPSTREAM_TOMCAT1="server $SERVER1_INTRANET_IP:$TOMCAT1_PORT;"
NGINX_UPSTREAM_TOMCAT2="server $SERVER2_INTRANET_IP:$TOMCAT2_PORT;"


# 0.防止误操作产生两个 Tomcat 都下线，如 Tomcat1 下线脚本退出
NGINX_CHECK_TOMCAT1_ONLINE=$(sudo cat $NGINX_CONFIG_FILE_BRAINMED | grep "$TAB$NGINX_UPSTREAM_TOMCAT1")
if [ "$NGINX_CHECK_TOMCAT1_ONLINE" != "$TAB$NGINX_UPSTREAM_TOMCAT1" ]; then
    echo "Tomcat1 未上线，不可部署 Tomcat2 ，请手动恢复***（Tomcat）环境，恢复成功再使用脚本部署。"
    exit 2
fi

# 1.从***开发/测试服务器的Tomcat1向***开发/测试服务器的Tomcat2同步需要部署的文件
echo "正在从***开发/测试服务器的Tomcat1向***开发/测试服务器的Tomcat2同步文件......"
rsync -vrtogp -e ssh --delete $TOMCAT1_DEPLOY_DIRECTORY $SERVER2_USER@$SERVER2_INTRANET_IP:$TOMCAT2_DEPLOY_DIRECTORY
echo "从***开发/测试服务器的Tomcat1向***开发/测试服务器的Tomcat2同步文件成功！"
echo ""

# 2.修改Nginx配置文件，将***开发/测试服务器的Tomcat2暂时下线
echo "正在将***开发/测试服务器的Tomcat2下线......"
sudo sed -i -e "s/$TAB$NGINX_UPSTREAM_TOMCAT2/$TAB#$NGINX_UPSTREAM_TOMCAT2/g" $NGINX_CONFIG_FILE_MEDTION
sudo sed -i -e "s/$TAB$NGINX_UPSTREAM_TOMCAT2/$TAB#$NGINX_UPSTREAM_TOMCAT2/g" $NGINX_CONFIG_FILE_BRAINMED
sudo docker exec -i nginx nginx -s reload 
echo "***开发/测试服务器的Tomcat2下线成功！"
echo ""

# 3.重启***开发/测试服务器的Tomcat2
# echo "正在将***开发/测试服务器的Tomcat2重启......"
# sudo $TOMCAT2_BIN_DIRECTORY/shutdown.sh
# echo ""
# echo "等待10秒后，强杀***开发/测试服务器的Tomcat2进程！"
# sleep 10
# sudo ps aux | grep $TOMCAT2_CATALINA_HOME | grep -v grep | awk '{print "sudo kill -9 " $2}' | sh
# echo ""
# sudo -u tomcat $TOMCAT2_BIN_DIRECTORY/startup.sh
# echo "***开发/测试服务器的Tomcat2重启成功！"
# echo ""

ssh $SERVER2_USER@$SERVER2_INTRANET_IP "sudo docker restart naoyihui_tomcat_user"

# 4.开发人员检查***开发/测试服务器的Tomcat2的日志，确认Tomcat成功启动，并且没有错误，此处只做确认，不做校验
echo "请检查***开发/测试服务器的Tomcat2的日志！"
while true
do
    read -r -p "确认Tomcat成功启动，并且没有错误？ [y/N] " input
    case $input in
        [yY][eE][sS]|[yY])
            break
            ;;
        *)
            ;;
    esac
done
echo ""

# 5.修改Nginx配置文件，将***开发/测试服务器的Tomcat2上线
echo "正在将***开发/测试服务器的Tomcat2上线......"
sudo sed -i -e "s/$TAB#$NGINX_UPSTREAM_TOMCAT2/$TAB$NGINX_UPSTREAM_TOMCAT2/g" $NGINX_CONFIG_FILE_MEDTION
sudo sed -i -e "s/$TAB#$NGINX_UPSTREAM_TOMCAT2/$TAB$NGINX_UPSTREAM_TOMCAT2/g" $NGINX_CONFIG_FILE_BRAINMED
sudo docker exec -i nginx nginx -s reload
echo "***开发/测试服务器的Tomcat2上线成功！"

